<template>
  <div class="h-screen flex flex-col bg-gray-50">
    <!-- 顶部导航栏 -->
    <TopNavBar />
    
    <!-- 语音处理进度弹窗 -->
    <VoiceTaskProgress 
      :show-progress="showProgress"
      :can-cancel="true"
      @cancel="handleProgressCancel"
    />
    
    <!-- 主体内容区 -->
    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧角色列表 -->
      <CharacterSidebar 
        :characters="characters"
        :selected-id="selectedCharacterId"
        @select="handleCharacterSelect"
        class="hidden md:flex"
      />
      
      <!-- 移动端角色选择抽屉 -->
      <el-drawer
        v-model="showCharacterDrawer"
        title="选择AI角色"
        direction="ltr"
        size="80%"
        class="md:hidden"
      >
        <CharacterSidebar 
          :characters="characters"
          :selected-id="selectedCharacterId"
          @select="handleCharacterSelectMobile"
        />
      </el-drawer>
      
      <!-- 右侧聊天主界面 -->
      <div class="flex-1 flex flex-col">
        <!-- 移动端顶部角色信息 -->
        <div class="md:hidden h-12 bg-white border-b border-gray-200 flex items-center px-4">
          <el-button 
            @click="showCharacterDrawer = true"
            size="small"
            class="mr-3"
          >
            <el-icon><Menu /></el-icon>
          </el-button>
          <div v-if="currentCharacter" class="flex items-center">
            <el-avatar :src="currentCharacter.avatarUrl" :size="28">
              <el-icon><Avatar /></el-icon>
            </el-avatar>
            <span class="ml-2 font-medium text-gray-800">{{ currentCharacter.name }}</span>
          </div>
        </div>
        
        <ChatMainPanel
          :character="currentCharacter"
          :messages="messages"
          :is-loading="isLoading"
          :is-recording="isRecording"
          :is-processing="isProcessing"
          @send-message="handleSendMessage"
          @send-voice="handleSendVoice"
          @toggle-progress-panel="handleToggleProgressPanel"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Menu, Avatar } from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'
import { useAuthStore } from '@/stores/auth'
import { blobToBase64 } from '@/utils/audio'

// 组件引入
import TopNavBar from '@/components/TopNavBar.vue'
import CharacterSidebar from '@/components/CharacterSidebar.vue' 
import ChatMainPanel from '@/components/ChatMainPanel.vue'
import VoiceTaskProgress from '@/components/VoiceTaskProgress.vue'

// Store
const chatStore = useChatStore()
const authStore = useAuthStore()

// 响应式数据
const selectedCharacterId = ref<number | null>(null)
const showCharacterDrawer = ref(false)

// 计算属性
const characters = computed(() => chatStore.characters)
const messages = computed(() => chatStore.messages)
const isLoading = computed(() => chatStore.isLoading)
const isRecording = computed(() => chatStore.isRecording)
const isProcessing = computed(() => chatStore.isProcessing)

// 流式处理相关
const showProgressPanel = ref(true) // 用户控制是否显示进度面板
const showProgress = computed(() => {
  return showProgressPanel.value && 
         (chatStore.taskStatus === 'PENDING' || 
          chatStore.taskStatus === 'PROCESSING' || 
          chatStore.taskStatus === 'COMPLETED' || 
          chatStore.taskStatus === 'FAILED')
})

const currentCharacter = computed(() => 
  characters.value.find(c => c.id === selectedCharacterId.value)
)

// 页面初始化
onMounted(async () => {
  try {
    // 检查登录状态
    if (!authStore.isAuthenticated) {
      ElMessage.error('请先登录')
      return
    }

    // 初始化语音设置
    await chatStore.initVoiceSettings()
    
    // 获取角色列表
    await chatStore.fetchCharacters()
    
    // 默认选择第一个角色
    if (characters.value.length > 0) {
      selectedCharacterId.value = characters.value[0].id
      await handleCharacterSelect(characters.value[0].id)
    } else {
      ElMessage.warning('暂无可用的AI角色')
    }
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面加载失败，请刷新重试')
  }
})

// 页面加载时初始化WebSocket
onMounted(async () => {
  await chatStore.initializeWebSocket()
})

// 页面离开时断开WebSocket连接
onBeforeUnmount(() => {
  chatStore.disconnectWebSocket()
})

// 事件处理
const handleCharacterSelect = async (characterId: number) => {
  try {
    selectedCharacterId.value = characterId
    await chatStore.switchCharacter(characterId)
  } catch (error) {
    console.error('切换角色失败:', error)
    ElMessage.error('切换角色失败')
  }
}

const handleCharacterSelectMobile = async (characterId: number) => {
  await handleCharacterSelect(characterId)
  showCharacterDrawer.value = false
}

const handleSendMessage = async (content: string) => {
  if (!selectedCharacterId.value) {
    ElMessage.warning('请先选择一个AI角色')
    return
  }
  
  try {
    await chatStore.sendMessage(content, 'text')
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  }
}

const handleSendVoice = async (audioBlob: Blob) => {
  if (!selectedCharacterId.value) {
    ElMessage.warning('请先选择一个AI角色')
    return
  }
  
  try {
    console.log('handleSendVoice 接收到的 audioBlob:', audioBlob)
    console.log('audioBlob 类型:', typeof audioBlob)
    console.log('是否为 Blob 实例:', audioBlob instanceof Blob)
    
    // 使用新的流式语音处理
    await chatStore.sendVoiceMessage(audioBlob)
  } catch (error) {
    console.error('发送语音消息失败:', error)
    ElMessage.error('发送语音消息失败，请重试')
  }
}

// 处理进度弹窗取消
const handleProgressCancel = () => {
  // 进度弹窗会自动隐藏，这里可以添加额外的清理逻辑
  console.log('用户取消了语音处理任务')
}

// 切换进度面板显示
const handleToggleProgressPanel = (show: boolean) => {
  showProgressPanel.value = show
  console.log('进度面板显示状态:', show)
}
</script>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .h-screen {
    height: 100vh;
    height: 100dvh; /* 动态视口高度，更适合移动设备 */
  }
}

/* 抽屉样式覆盖 */
:deep(.el-drawer__body) {
  padding: 0;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}
</style>

